import { DD_AUTH, DD_SYSTEM } from '@/constants/api-pre';
import { request } from '../request';

/**
 * Password-Login
 *
 * @param username User name
 * @param password Password
 * @param code 验证码
 * @param key 验证码key
 * @param grant_type 登录类型
 */
// eslint-disable-next-line max-params
export function fetchLogin(username: string, password: string, code: string, key: string, grant_type: string) {
  return request<Api.Auth.LoginToken>({
    url: `${DD_AUTH}/oauth2/token`,
    method: 'post',
    params: {
      username,
      password,
      code,
      key,
      grant_type
    }
  });
}

/** Get user info */
export function fetchGetUserInfo() {
  return request<Api.Auth.UserInfo>({ url: `${DD_SYSTEM}/users/me` });
}

/**
 * Refresh token
 *
 * @param refreshToken Refresh token
 */
export function fetchRefreshToken(refreshToken: string) {
  return request<Api.Auth.LoginToken>({
    url: `${DD_AUTH}/oauth2/token`,
    method: 'post',
    data: {
      refresh_token: refreshToken,
      grant_type: 'refresh_token'
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
}

/**
 * return custom backend error
 *
 * @param code error code
 * @param msg error message
 */
export function fetchCustomBackendError(code: string, msg: string) {
  return request({ url: '/auth/error', params: { code, msg } });
}
